package cn.mania_man.trpg_helper_server.websocket;

import cn.mania_man.trpg_helper_server.room.ResponseMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MessageSender {
    private static final Map<String, Timer> messageTimers = new ConcurrentHashMap<>();
    private static final Map<String, ResponseMessage> messages = new ConcurrentHashMap<>();

    private static  final Logger logger = LoggerFactory.getLogger(MessageSender.class);
    private static class sendTask extends TimerTask {
        private final ResponseMessage message;
        public sendTask(ResponseMessage message) {
            this.message = message;
        }

        @Override
        public void run() {
            message.send();
            if (message.getReceivers().size()==0){
                messageTimers.get(message.getMsgId()).cancel();
                messages.remove(message.getMsgId());
                messageTimers.remove(message.getMsgId());
            }
        }
    }
    public static void finishMessage(String msgId,User user){
        try {
            ResponseMessage msg= messages.get(msgId);
            msg.getReceivers().remove(user);
            if (msg.getReceivers().size()==0){
                messageTimers.get(msgId).cancel();
                messages.remove(msgId);
                messageTimers.remove(msgId);
            }
        } catch (NullPointerException e) {
            throw new RuntimeException(e);
        }

    }
    public static void PushMessage(ResponseMessage msg) {
        logger.info("开始发送请求:"+msg.getType()+"接收者:"+ Arrays.toString(msg.getReceivers().stream().map(User::getUserName).toArray()));
        String msgId = "";
        while (messageTimers.containsKey(msgId) || msgId.equals("")) {
            msgId = (int) (Math.random() * 100000000) + "";
        }
        msg.setMsgId(msgId);
        Timer timer =new Timer();
        sendTask task =new sendTask(msg);
        timer.schedule(task,300);
        messageTimers.put(msgId,timer);
        messages.put(msgId,msg);
        task.run();
    }
}
